<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Admin\CommonController;
use App\Models\AnswerActivity;
use App\Models\AnswerActivityRanking;
use App\Models\AnswerActivityUnit;
use App\Models\AnswerActivityUserCorrectTotalNumber;
use App\Models\AnswerActivityUserGift;
use App\Models\AnswerActivityUserUnit;
use App\Models\UserInfo;
use App\Validate\AnswerActivityRankingValidate;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * 活动排行榜管理
 */
class AnswerActivityRankingController extends CommonController
{

    public $model = null;
    public $activityModel = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new AnswerActivityRanking();
        $this->activityModel = new AnswerActivity();
        $this->validate = new AnswerActivityRankingValidate();
    }

    /**
     * 活动排名
     * @param token int 用户token
     * @param act_id int 活动id
     * @param unit_id int 单位id  除独立活动外，若传了则是单位排名，不传则是总排名  ；独立活动，单位排名等于独立排名
     * @param page int 页码
     * @param limit int 分页大小
     */
    public function ranking()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('ranking')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        if (!empty($this->request->page) && $this->request->page > 50) {
            return $this->returnApi(203, '暂无数据'); //超过500名不显示
        }

        $act_info = $this->activityModel->detail($this->request->act_id, [], null);

        if (empty($act_info)) {
            return $this->returnApi(201, '参数错误');
        }

        // 判断 今日上一次是否主动提交，没有需要手动提交一次 ,只处理轮次排名
        if ($act_info['pattern'] == 2) {
            $activityUserCorrectTotalNumber = new AnswerActivityUserCorrectTotalNumber();
            $activityUserCorrectTotalNumber->lastCorrectGuestPosting($act_info['id'], null, $act_info['answer_time'], $act_info['answer_number'], $act_info['node']);
        }

        if ($act_info['node'] == 1 && !empty($this->request->unit_id)) {
            return $this->returnApi(201, '此活动为独立活动，不允许选择单位');
        }
        $cache_key = md5($this->request->token . $this->request->act_id . $this->request->unit_id . $this->request->page . $this->request->limit);
        $cache_rank = Cache::get($cache_key);
        if ($cache_rank) {
            return $this->returnApi(200, '获取成功', true, $cache_rank);
        }

        $res = $this->model->getRanking($act_info['pattern'], $this->request->act_id, $this->request->unit_id, $this->request->limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }

        $res = $this->disPageData($res);

        $userInfoModel = new UserInfo();
        $commonController = new CommonController();
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['user_info'] = $userInfoModel->getWechatInfo($val['user_guid']);
            $res['data'][$key]['rank'] = $commonController->addSerialNumberOne($key, $this->request->page, $this->request->limit);
            $res['data'][$key]['times'] = second_to_time($val['times']);
        }

        //获取用户排名
        $self_rank = $this->model->userRanking($act_info['pattern'], $this->request->act_id, $this->request->unit_id, $this->request->token);

        $res['self_rank'] = $self_rank;
        $res['self_rank']['user_info'] = $userInfoModel->getWechatInfo($this->request->token);

        Cache::put($cache_key, $res, 60); //缓存一分钟

        return $this->returnApi(200, '获取成功', true, $res);
    }


    /**
     * 我的成绩单
     * @param act_id 活动id
     * @param token int 用户token
     */
    public function myGrade()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('grade')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $act_info = $this->activityModel->detail($this->request->act_id);
        if (empty($act_info)) {
            return $this->returnApi(202, '暂无成绩信息');
        }

        //获取答题数，获取正确率
        $model = $this->activityModel->getAnswerTotalRecordModel($act_info['pattern']);
        $answer_data = $model->getAnswerTotelData($this->request->act_id, 0, $this->request->token);

        $data['pattern'] = $act_info['pattern'];
        $data['prize_form'] = $act_info['prize_form'];
        if (!empty($answer_data)) {
            $data['answer_number'] = $answer_data['answer_number']; //答题数量
            $data['correct_number'] = $answer_data['correct_number']; //答题正确数量
            $data['accuracy'] = $answer_data['accuracy']; //答题正确率
        } else {
            $data['answer_number'] = 0; //答题数量
            $data['correct_number'] = 0; //答题正确数量
            $data['accuracy'] = 0; //答题正确率
        }

        // prize_form 获奖情况  1 排名  2 抽奖
        if ($act_info['prize_form'] == 1) {
            $data['self_rank'] = $this->model->userRanking($act_info['pattern'], $this->request->act_id, 0, $this->request->token);
        } else {
            $answer_activity_gift_type = config('other.answer_activity_gift_type');
            if (in_array(1, $answer_activity_gift_type)) {
                $answerActivityUserGiftModel = new AnswerActivityUserGift();
                $data['red_number'] = $answerActivityUserGiftModel->getWinNumber($this->request->act_id, $this->request->token, 1);
            }

            if (in_array(2, $answer_activity_gift_type)) {
                $answerActivityUserGiftModel = new AnswerActivityUserGift();
                $data['gift_number'] = $answerActivityUserGiftModel->getWinNumber($this->request->act_id, $this->request->token, 2);
            }
        }
        if ($act_info['node'] == 1) {
            $unit_qr_url = $act_info['qr_url'];
        } else {
            $unit_qr_url = null;
            $answerActivityUserUnitModel = new AnswerActivityUserUnit();
            $select_unit = $answerActivityUserUnitModel->isSelectUnit($this->request->token, $this->request->act_id);
            if ($select_unit) {
                $unit_id = $select_unit['unit_id'];
            } else {
                $unit_id = 0;
            }
            $answerActivityUnitModel = new AnswerActivityUnit();
            $unit_qr_url_info = $answerActivityUnitModel->detail($unit_id);
            if ($unit_qr_url_info) {
                $unit_qr_url = $unit_qr_url_info['qr_url'];
            }
            if (empty($unit_qr_url)) {
                $unit_qr_url_info = $answerActivityUnitModel->detailByActId($this->request->act_id, ['qr_url']);
                if ($unit_qr_url_info) {
                    $unit_qr_url = $unit_qr_url_info['qr_url'];
                }
            }
        }

        $data['qr_url'] = $unit_qr_url; //最多15个字 
        // $data['slogan1'] = $act_info['slogan1'] ? $act_info['slogan1'] : '读书破万卷，下笔如有神，没错，是你了~'; //最多15个字
        //  $data['slogan2'] = $act_info['slogan2'] ? $act_info['slogan2'] : '立即扫码，获得您的阅读成绩'; //最多15个字


        //获取用户昵称和头像
        $user_info = UserInfo::getInstance()->getWechatInfo($this->request->token);
        $data['nickname'] = $user_info['nickname'];
        $data['head_img'] = $user_info['head_img'];

        return $this->returnApi(200, '获取成功', true, $data);
    }
}
